/** 问好 */
export function timeFix() {
  const time = new Date();
  const hour = time.getHours();
  return hour < 9
    ? '早上好'
    : hour <= 11
    ? '上午好'
    : hour <= 13
    ? '中午好'
    : hour < 20
    ? '下午好'
    : '晚上好';
}

/**
 * 字符串首字母转大写
 * @param {String} str 被转换字符
 */
export const firstUpperCase = str => {
  if (typeof str !== 'string') return '';
  return (
    str.substr(0, 1).toLocaleUpperCase() + str.substr(1).toLocaleLowerCase()
  );
};

// 有路由没组件时显示
const Incomplete = {
  render(h) {
    return h('p-result', {
      props: {
        status: '500',
        title: '页面正在开发中...',
      },
      style: {
        width: '100%',
      },
    });
  },
};

/** 时间戳转化 */
export function formatDate(dates) {
  let date = new Date(dates);
  var YY = date.getFullYear() + '-';
  var MM =
    (date.getMonth() + 1 < 10
      ? '0' + (date.getMonth() + 1)
      : date.getMonth() + 1) + '-';
  var DD = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
  var hh =
    (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
  var mm =
    (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) +
    ':';
  var ss = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
  return YY + MM + DD + ' ' + hh + mm + ss;
}

/**
 * 获取页面组件
 * @param {String} componentPath 组件相对路径（@/views）
 */
export const getViewComponent = (function() {
  const load = path => {
    try {
      return require(`@/views${path}`);
    } catch (err) {
      return null;
    }
  };
  return function(componentPath) {
    const paths = ['', '/index.vue', '.js', '.vue'].map(
      suffix => componentPath + suffix
    );
    let component = null;
    let path = paths.shift();
    while (path) {
      component = load(path);
      if (component) return component.default || component;

      path = paths.shift();
    }
    return Incomplete;
  };
})();

/**
 * 获取布局组件
 * @param {String} name 布局组件名称
 */
export const getLayoutComponent = (function() {
  const load = path => {
    try {
      return require(`@/layouts/${path}`);
    } catch (err) {
      return null;
    }
  };
  return function(name) {
    const paths = ['', '.js', '.vue', '/index.vue'].map(
      suffix => name + suffix
    );
    let component = null;
    for (let j in paths) {
      component = load(paths[j]);
      if (component) return component.default || component;
    }
  };
})();

/* 校验 URL
 * @params {string} string - 待校验字符串
 * @return {boolean}
 * */
export function isURL(string) {
  const str =
    '(http(s)?://.)(www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{2,256}\\.[a-z]{2,6}\\b([-a-zA-Z0-9@:%_\\+.~#?(&|&amp;)//=]*)';
  const reg = new RegExp(str, 'i');
  return reg.test(string);
}

/* 判断 页面 是否在 iframe 打开
 * @return {boolean}
 * */
export const isIframeOpen =
  window.frameElement && window.frameElement.tagName === 'IFRAME';

/* 判断 当前 是否是 开发环境
 * @return {boolean}
 * */
export const isDev = process.env.NODE_ENV === 'development';

// 下载文件
export async function downloadFile(data, filename = '文件.xls') {
  // 获取文件流
  const a = document.createElement('a');
  const blob = new Blob([data]);
  const url = window.URL.createObjectURL(blob);
  a.href = url;
  a.download = `${filename}`;
  a.click();
  window.URL.revokeObjectURL(url);
}

// 数组、对象深拷贝
export const deepClonel = (obj) => {
  let objClone = Array.isArray(obj) ? [] : {}
  if (obj && typeof obj === 'object') {
    for (let key in obj) {
      if (obj.hasOwnProperty(key)) {
        if (obj[key] && typeof obj[key] === 'object') {
          objClone[key] = deepClonel(obj[key])
        } else {
          objClone[key] = obj[key]
        }
      }
    }
  }
  return objClone
}

// JSON深拷贝

export const deepClonelJSON = (obj) => {
  let objClone = JSON.stringify(obj);
  let _obj = JSON.parse(objClone)
  return _obj
}